<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ include file="/public/header.jsp"%>
<%
    String callback = request.getParameter("callback");
	String isShow = request.getParameter("isShow") == null ? "" : request.getParameter("isShow");
	String return_id = request.getParameter("return_id") == null ? "" : request.getParameter("return_id");
	Map<String, Object> sessionMap = (Map<String, Object>) session.getAttribute("LOGIN_USER");
	String person_id = String.valueOf(sessionMap.get("id"));
	String person = String.valueOf(sessionMap.get("truename"));
	boolean isAdd = "".equals(return_id);
    int flag = 0;
    if(!isAdd){
    	flag = 1;
    }
%>
<html>
	<head>
		<title><%=isAdd?"新建工余库还料":"编辑工余库还料" %></title>
		<script type="text/javascript" src="<%=contextPath %>/public/js/extend.js"></script>
		<style>
			.td1{
				padding-top:10px;
				padding-bottom:5px;
				font-size: 12px;
				background-color: #c0ebd7;
				width:20%;
			}
			.td2{
				padding:5px;
			}
		</style>
	<script type="text/javascript">
	var lastIndex;
	var flag="<%=flag%>";
	$(function(){
			if('<%=flag%>' == 1){
				$('#ff').form('load','<%=contextPath %>/springMVC/gd/getCustomerReturnById?return_id=<%=return_id%>');
			}else{
			    jQuery("#operation_date").datetimebox('setValue',getTodaySecond());
			}
			$('#table').datagrid({
				<%=isAdd?"url:'',":"url:'"+contextPath+"/springMVC/gd/listGDCustomerReturnDetail?return_id="+return_id+"',"%>
				rownumbers:true,
				fitColumns:true,
				nowrap:false,
				frozenColumns:[[
					{field:'ck',checkbox:true},
				    {title:'借料明细id',field:'borrow_detail_id',hidden:true},
				    {title:'项目id',field:'xm_id',hidden:true}
				]],
				columns:[[
					{title:'工单编号',field:'gd_code',width:120,align:'center'},
					{title:'工单名称',field:'gd_name',width:180,align:'center'},
					{title:'借料编号',field:'borrow_code',width:120,align:'center'},     
					{title:'产品id',field:'material_id',hidden:true},
					{title:'产品编号',field:'code',width:100,align:'center'},
					{title:'产品名称',field:'name',width:100,align:'center'},
					{title:'规格/型号',field:'format_type',width:150,align:'center'},
					{title:'单位',field:'unit_name',width:50,align:'center'},
					{title:'借料数量',field:'borrow_num',width:80,align:'center'},
					{title:'已还数量',field:'already_return_num',width:80,align:'center'},
					{title:'还钱',field:'return_money',hidden:true},
					<%if(!"1".equals(isShow)){%>
					{title:'当前项目库数量',field:'project_num',width:100,align:'center',formatter:function(value,row,index){
						var xm_id= jQuery("#xm_id").val();
						if(value == undefined){
							$.ajax({
								type:'POST',
								url:'<%=contextPath %>/springMVC/gd/getProjectMaterialNum?material_id='+row.material_id+'&xm_id='+xm_id,
								async:false,
								success:function(rtJson){
									if(rtJson == 'no'){
										row.project_num =0;
									}else{
										row.project_num = rtJson;
									}
								}
							});
							return row.project_num;
						}
						return row.project_num;
					}},
					<%}%>
					{title:'还料数量',field:'return_num',width:100,align:'center',editor:{
						type:'numberbox',
						options:{
							min:0,
							precision:2
						}
					}},
					{title:'备注',field:'remark',width:100,align:'center',editor:{
						type:'textarea'
					}}
				]],
				onBeforeLoad:function(){
					$(this).datagrid('rejectChanges');
				},
				onClickCell:function(rowIndex,field,value){
					if (lastIndex != rowIndex){
						$('#table').datagrid('endEdit', lastIndex);
						$('#table').datagrid('beginEdit', rowIndex);
						var ed = $('#table').datagrid('getEditor', {index:rowIndex,field:field});
						if(ed == null){
							ed = $('#table').datagrid('getEditor', {index:rowIndex,field:'return_num'});
						}
						$(ed.target).select();
					}
					lastIndex = rowIndex;
				},
				toolbar:[
					{
						id:'add',
						text:'选择借料单',
						disabled:false,
						iconCls:'icon-add',
						handler:function(){
							var xm_id=jQuery("#xm_id").val();
							if(xm_id==''){
								$.messager.alert("提示","请先选择项目！");
								return;
							}
							openDialogResize("<%=contextPath %>/springViews/xm/chooseBorrow.jsp?callback=addRows&type=1&xm_id="+xm_id,1000, 800);
						}
					},'-',{
					id:'save',
					text:'保存修改',
					disabled:false,
					iconCls:'icon-save',
					handler:function(){
						$('#table').datagrid('acceptChanges');
						lastIndex =-1;
					}
					},'-',{
					id:'delete',
					text:'删除',
					disabled:false,
					iconCls:'icon-remove',
					handler:function(){
						$('#table').datagrid('acceptChanges');
						lastIndex =-1;
						var rows = $('#table').datagrid('getSelections');
						if (rows.length > 0){
							for(var i=0;i<rows.length;i++){
								var row = rows[i];
								var index = $('#table').datagrid('getRowIndex', row);
								$('#table').datagrid('deleteRow', index);
							}
						}
						var data = $('#table').datagrid('getData');
						$('#table').datagrid('loadData',data);
					}
				}
			   ]
			});
		});
		
		function addRows(ids,gd_codes,gd_names,borrow_codes,material_ids,operation_dates,summarys,codes,names,format_types,unit_names,borrow_nums,already_return_nums){
			
			 if(ids==""){
				  return;
			 }
			 var idArray= new Array();
			 var gdCodeArray= new Array();
			 var gdNameArray= new Array();
			 var borrowCodeArray= new Array();
			 var materialIdArray= new Array();
			 var operationDateArray= new Array();
			 var summaryArray= new Array();
			 var codeArray= new Array();
			 var nameArray= new Array();
			 var formatTyperay= new Array();
			 var unitNameArray= new Array();
			 var borrowNumArray= new Array();
			 var alreadyReturnNumArray= new Array();
			 idArray=ids.split(",");
			 gdCodeArray=gd_codes.split(",");
			 gdNameArray=gd_names.split(",");
			 borrowCodeArray=borrow_codes.split(",");
			 materialIdArray=material_ids.split(",");
			 operationDateArray=operation_dates.split(",");
			 summaryArray=summarys.split(",");
			 codeArray=codes.split(",");
			 nameArray=names.split(",");
			 formatTyperay=format_types.split(",");
			 unitNameArray=unit_names.split(",");
			 borrowNumArray=borrow_nums.split(",");
			 alreadyReturnNumArray=already_return_nums.split(",");
		     for (var i=0;i<idArray.length ;i++ )   
		     {
		    	 addRow(idArray[i],gdCodeArray[i],gdNameArray[i],borrowCodeArray[i],materialIdArray[i],operationDateArray[i],summaryArray[i],codeArray[i],nameArray[i],formatTyperay[i],unitNameArray[i],borrowNumArray[i],alreadyReturnNumArray[i]);
		     }
		}
		function addRow(borrow_detail_id,gd_code,gd_name,borrow_code,material_id,operation_date,summary,code,name,format_type,unit_name,borrow_num,already_return_num){
			$('#table').datagrid('endEdit', lastIndex);
			$('#table').datagrid('appendRow',{
				borrow_detail_id:borrow_detail_id,
				gd_code:gd_code,
				gd_name:gd_name,
				borrow_code:borrow_code,
				material_id:material_id,
				operation_date:operation_date,
				summary:summary,
				code:code,
				name:name,
				format_type:format_type,
				unit_name:unit_name,
				borrow_num:borrow_num,
				already_return_num:already_return_num,
				return_money:'0',
				return_num:borrow_num-already_return_num
			});
			var data = $('#table').datagrid('getData');
			$('#table').datagrid('loadData',data);
			lastIndex = $('#table').datagrid('getRows').length-1;
			$('#table').datagrid('selectRow', lastIndex);
			$('#table').datagrid('beginEdit', lastIndex);
		}
		
		function addGDMaterialRequest(obj){
			//自动提交数据
			$('#table').datagrid('acceptChanges');
			lastIndex =-1;
			//自动提交数据
			if($('#ff').form('validate')){
				var products="";
				var jsondata=$("#table").datagrid("getData");
				for(var i=0;i<jsondata.total;i++){
					if(products!=""){
						products+=";";
					}
					products+=jsonToStr(jsondata.rows[i]);
					var index = $("#table").datagrid("getRowIndex",jsondata.rows[i])+1;
					if(jsondata.rows[i].return_num == null || jsondata.rows[i].return_num <= 0){
						$.messager.alert('提示','第'+index+'行还料数量填写不正确！');
						return ;
					}
					if(parseFloat(jsondata.rows[i].return_num) > parseFloat(jsondata.rows[i].project_num)){
						$.messager.alert('提示','第'+index+'行还料数量不能大于库存数量！');
						return ;
					}
					if(parseFloat(jsondata.rows[i].return_num)>parseFloat(parseFloat(jsondata.rows[i].borrow_num)-parseFloat(jsondata.rows[i].already_return_num))){
						$.messager.alert('提示','第'+index+'行还料数量不能大于借料数量！');
						return ;
					}
				}
				var xm_id = $('#xm_id').val();
				var xm_code = $('#xm_code').val();
				var xm_name = $('#xm_name').val();
				var dept_id = $('#dept_id').val();
				var dept_name = $('#dept_name').val();
				var warehouse_id = $("#warehouse_id").val();
				var warehouse_name = $("#warehouse_name").val();
				if(!checkNullOREmpty(xm_id,'项目为必填项')){return;}
				if(!checkNullOREmpty(warehouse_id,'仓库为必填项')){return;}
				if(!checkNullOREmpty(products,'还料为必填项')){return;}
				var operation_date = $("#operation_date").datetimebox('getValue');
				var remark = encodeURIComponent($('#remark').val());
			
				
				var param = "warehouse_id="+warehouse_id+"&warehouse_name="+warehouse_name+"&xm_id="+xm_id+"&xm_code="+xm_code+"&xm_name="+xm_name+"&dept_id="+dept_id+"&dept_name="+dept_name+"&type=1&person_id=<%=person_id%>&person=<%=person%>&operation_date="+operation_date+"&remark="+remark+"&products="+products;
				$(obj).hide();
				$.ajax({
					type:'POST',
					<%=isAdd?"url:'"+contextPath+"/springMVC/gd/addGDCustomerReturn',":"url:'"+contextPath+"/springMVC/gd/updateGDCustomerReturn?return_id="+return_id+"',"%>
					data:param,
					dataType:'json',
					success:function(rtJson){
						if(rtJson.rtState == '0'){
							eval('window.opener.<%=callback%>();');
							window.close();
						}
						else{
							$.messager.alert("提示",rtJson.rtMsrg);
						}
						$(obj).show();
					}
				});
			}
		}
	function choseXm(){
	    openDialogResize("<%=contextPath %>/springViews/xm/choseMyXM.jsp?statusType=7",1000, 800);
	}
	function rtCallBackXmSet(xm_id,xm_code,xm_name,deptId,dept,customer_id,customer){
		 jQuery("#xm_id").val(xm_id);
	      jQuery("#xm_name").val(xm_name);
	      jQuery("#xm_code").val(xm_code);
	      jQuery("#dept_name").val(dept);
	      jQuery("#dept_id").val(deptId);
	      var url='<%=contextPath %>/springMVC/warehouse/getWareHouseById?type=1&dept_id='+deptId;
			$.ajax({
				type:'GET',
				url:url,
				dataType:'json',
				success:function(rtJson){
					 jQuery("#warehouse_id").val(rtJson.id);
					 jQuery("#warehouse_name").val(rtJson.name);
				}
			});
	}
	</script>
	</head>
	<body>
		<div style="width: 97%;padding-left:10px">
		<form id="ff">
			<table  style="border-collapse: collapse;" width="100%" border="1px" bordercolor="#0eb83a">
				<tr>
					<td align="right" class="td1" nowrap>项目编号：</td>
					<td class="td2" nowrap>
						<input  id="xm_code" name="xm_code" readOnly  >
						<input type="hidden" id="xm_id" name="xm_id" readOnly  >
						<a href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'icon-add',plain:false" onclick="choseXm();"></a>								</td>
	
					</td>
					<td align="right" class="td1" nowrap>项目名称：</td>
					<td class="td2" nowrap>
						<input  id="xm_name" name="xm_name" readOnly >
					</td>
				</tr>
				<tr>
					<td align="right" class="td1" nowrap>项目部门：</td>
					<td class="td2" nowrap>
						<input  id="dept_name" name="dept_name" readOnly  >
						<input  type="hidden" id="dept_id" name="dept_id" readOnly  >
					</td>
					<td align="right" class="td1" nowrap>申请人：</td>
					<td class="td2" nowrap>
						<input  id="person" name="person" readOnly value="<%=person%>">
					</td>
				</tr>
				<tr>

					<td align="right" class="td1" nowrap>仓库：</td>
					<td class="td2" nowrap>
						<input  id="warehouse_id" name="warehouse_id" type="hidden">
						<input  id="warehouse_name" name="warehouse_name" readonly="readonly" >
					</td>	
					<td align="right" class="td1" nowrap>申请日期：</td>
					<td class="td2" nowrap  >
						<input  id="operation_date" name="operation_date" class="easyui-datetimebox" data-options="required:true">
					</td>
				</tr>
				<tr>
					<td align="right" class="td1" nowrap>摘要：</td>
					<td class="td2" nowrap colspan='3'>
						<textarea  id="remark" name="remark" rows="6" style="width: 100%"></textarea>
					</td>
				</tr>
				   <%if(!"1".equals(isShow)){ %>
				<tr>
					<td align="right" class="td1" nowrap></td>
					
					<td class="td2" nowrap colspan='3'>
						<div align="left">
							<a href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'icon-save',plain:false" onclick="addGDMaterialRequest(this);">提交</a>
							<a href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'icon-cancel',plain:false" onclick="javascript:window.close();">关闭</a>
						</div>
					</td>
				</tr>
				<%} %>
				<tr>
					<td colspan="4"  nowrap>
						<div id="table"></div>
					</td>
				</tr>
			</table>
			</form>
		</div>
		
	</body>
</html>